package JaggSoft;

import JaggSoft.Utilidades.*;
import java.awt.Point;
import java.awt.event.KeyEvent;
import javax.swing.*;

public class Devoluciones extends javax.swing.JInternalFrame {
    public Devoluciones() {
        initComponents();
        this.setLocation(new Point(70,0));
        this.jpObservacion.setVisible(false);
        jbtnGuardar.setEnabled(false);
        jbtnCancelar.setEnabled(false);
    }
    private ModeloItemValor[] getItemsComboBox(){
        String[] columnas={"id","nombre"};
        JTable tabla=Conexion.ObtenerTabla("SELECT id_bodega,nombre FROM bodega;",columnas);
        ModeloItemValor[] items=new ModeloItemValor[tabla.getRowCount()+1];
        items[0]=new ModeloItemValor("-Ninguno-","-1");
        for(int i=0;i<tabla.getRowCount();i++)
            items[i+1]=new ModeloItemValor(tabla.getValueAt(i,1).toString(),tabla.getValueAt(i,0).toString());
        return items;
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jtfCodigoSolicitud = new javax.swing.JTextField();
        jbtnBuscar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtblDevolucion = new javax.swing.JTable();
        jpAccion = new javax.swing.JPanel();
        jbtnCancelar = new javax.swing.JButton();
        jbtnGuardar = new javax.swing.JButton();
        jlSolicitante = new javax.swing.JLabel();
        jtfSolicitante = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jtfFechaSolicitud = new javax.swing.JTextField();
        jpObservacion = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtaObservacion = new javax.swing.JTextArea();
        jlSolicitante1 = new javax.swing.JLabel();

        setClosable(true);
        setMaximizable(true);
        setTitle("Devolución de Producto");
        setVisible(true);

        jLabel1.setText("Código de Solicitud:");

        jtfCodigoSolicitud.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jtfCodigoSolicitudKeyPressed(evt);
            }
        });

        jbtnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_buscar_mini.png"))); // NOI18N
        jbtnBuscar.setToolTipText("Buscar");
        jbtnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnBuscarActionPerformed(evt);
            }
        });

        jScrollPane1.setViewportView(jtblDevolucion);

        jpAccion.setBorder(javax.swing.BorderFactory.createTitledBorder("Acciones"));

        jbtnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_cancelar.png"))); // NOI18N
        jbtnCancelar.setToolTipText("Cancelar");
        jbtnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnCancelarActionPerformed(evt);
            }
        });

        jbtnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/accion_guardar.png"))); // NOI18N
        jbtnGuardar.setToolTipText("Guardar");
        jbtnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnGuardarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jpAccionLayout = new javax.swing.GroupLayout(jpAccion);
        jpAccion.setLayout(jpAccionLayout);
        jpAccionLayout.setHorizontalGroup(
            jpAccionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpAccionLayout.createSequentialGroup()
                .addComponent(jbtnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        jpAccionLayout.setVerticalGroup(
            jpAccionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jbtnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jbtnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        jlSolicitante.setText("Solicitante:");

        jtfSolicitante.setEditable(false);

        jLabel2.setText("Fecha de Solicitud:");

        jtfFechaSolicitud.setEditable(false);

        jtaObservacion.setEditable(false);
        jtaObservacion.setColumns(20);
        jtaObservacion.setRows(5);
        jScrollPane2.setViewportView(jtaObservacion);

        jlSolicitante1.setText("Observación:");

        javax.swing.GroupLayout jpObservacionLayout = new javax.swing.GroupLayout(jpObservacion);
        jpObservacion.setLayout(jpObservacionLayout);
        jpObservacionLayout.setHorizontalGroup(
            jpObservacionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpObservacionLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jlSolicitante1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 530, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(64, 64, 64))
        );
        jpObservacionLayout.setVerticalGroup(
            jpObservacionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpObservacionLayout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(jpObservacionLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jlSolicitante1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jpObservacion, javax.swing.GroupLayout.PREFERRED_SIZE, 615, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                        .addComponent(jLabel2)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jtfFechaSolicitud))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel1)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jtfCodigoSolicitud, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbtnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jlSolicitante)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtfSolicitante, javax.swing.GroupLayout.PREFERRED_SIZE, 280, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jpAccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jpAccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jlSolicitante)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jbtnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel1)
                                    .addComponent(jtfCodigoSolicitud)))
                            .addComponent(jtfSolicitante, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jtfFechaSolicitud, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jpObservacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void jbtnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnBuscarActionPerformed
        if(!jtfCodigoSolicitud.getText().equals(""))
            Buscar(jtfCodigoSolicitud.getText());
        else
            JOptionPane.showMessageDialog(null,"Debe ingresar un código de solicitud.","Falta Código de Solicitud",JOptionPane.WARNING_MESSAGE);
    }//GEN-LAST:event_jbtnBuscarActionPerformed
    private void Buscar(String devolucion){
        String[] columnas={"id","Nombre","Unidad de Medida","Detalle","Prestado","Devuelto","Cantidad a Devolver","Pendiente","Bodega"};
        boolean[] cols_edit={false,false,false,false,false,false,true,false,true};
        Util.CargarTablaEditable(jtblDevolucion,"CALL VerDevolucion("+devolucion+")", columnas,cols_edit);
        Util.OcultarColumna(jtblDevolucion,0);
        Util.EstablecerColumnaCombobox(jtblDevolucion,8,getItemsComboBox());
        for(int i=0;i<jtblDevolucion.getRowCount();i++){
            int prestado=new Integer(jtblDevolucion.getValueAt(i,4).toString());
            int devuelto=new Integer(jtblDevolucion.getValueAt(i,5).toString());
            jtblDevolucion.setValueAt(prestado-devuelto,i,7);
        }
        JTable tabla=Conexion.ObtenerTabla("SELECT CONCAT_WS(' ',se.nombres,se.apellidos) AS nombre,DATE_FORMAT(sd.fecha,'%d/%m/%Y') AS fecha,sd.observacion FROM solicitud sd INNER JOIN solicitante se ON sd.id_solicitante=se.id_solicitante WHERE sd.id_solicitud="+devolucion,new String[]{"nombre","fecha","observacion"});
        if(tabla.getRowCount()>0){
            jtfSolicitante.setText(tabla.getValueAt(0,0).toString());
            jtfFechaSolicitud.setText(tabla.getValueAt(0,1).toString());
            String obs=tabla.getValueAt(0,2).toString();
            jtaObservacion.setText((obs.length()>0?obs:""));
            this.jpObservacion.setVisible(!jtaObservacion.getText().equals(""));
            jbtnGuardar.setEnabled(true);
            jbtnCancelar.setEnabled(true);
        }
        //System.err.println(jtblDevolucion.getValueAt(0,8).toString()); //test
    }
    private void jbtnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnCancelarActionPerformed
        System.err.println(((ModeloItemValor)jtblDevolucion.getColumnModel().getColumn(8).getCellEditor().getCellEditorValue()).getValor()); //test
        /*jbtnGuardar.setEnabled(false);
        jbtnCancelar.setEnabled(false);
        jtfCodigoSolicitud.setText("");
        jtfFechaSolicitud.setText("");
        jtaObservacion.setText("");
        jpObservacion.setVisible(false);*/
    }//GEN-LAST:event_jbtnCancelarActionPerformed
    private void jbtnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnGuardarActionPerformed
        Guardar();
    }//GEN-LAST:event_jbtnGuardarActionPerformed
    private void Guardar(){
        if(Validar()){
            
        }
        else
            JOptionPane.showMessageDialog(null,"Alguna cantidad de devolución es mayor que la posible o no ha seleccionado la bodega de alguna cantidad de devolución mayor que cero.","Cantidad o Bodega no establecido",JOptionPane.WARNING_MESSAGE);
    }
    private boolean Validar(){
        for(int i=0;i<jtblDevolucion.getRowCount();i++){
            int prestado=new Integer(jtblDevolucion.getValueAt(i,4).toString());
            int devuelto=new Integer(jtblDevolucion.getValueAt(i,5).toString());
            int cantidad=new Integer(jtblDevolucion.getValueAt(i,6).toString());
            int id_bodega=new Integer(((ModeloItemValor)jtblDevolucion.getColumnModel().getColumn(8).getCellEditor().getCellEditorValue()).getValor());
            if(id_bodega!=-1){
                if(prestado-devuelto-cantidad<0||cantidad==0)
                    return false;
            }
            else{
                System.err.println("["+id_bodega+"-"+cantidad+"]");
                if(cantidad>0) 
                    return false;
            }
        }
        return true;
    }
    private void jtfCodigoSolicitudKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfCodigoSolicitudKeyPressed
        if(evt.getKeyCode()==KeyEvent.VK_ENTER){
            if(!jtfCodigoSolicitud.getText().equals(""))
                Buscar(jtfCodigoSolicitud.getText());
            else
                JOptionPane.showMessageDialog(null,"Debe ingresar un código de solicitud.","Falta Código de Solicitud",JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_jtfCodigoSolicitudKeyPressed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton jbtnBuscar;
    private javax.swing.JButton jbtnCancelar;
    private javax.swing.JButton jbtnGuardar;
    private javax.swing.JLabel jlSolicitante;
    private javax.swing.JLabel jlSolicitante1;
    private javax.swing.JPanel jpAccion;
    private javax.swing.JPanel jpObservacion;
    private javax.swing.JTextArea jtaObservacion;
    private javax.swing.JTable jtblDevolucion;
    private javax.swing.JTextField jtfCodigoSolicitud;
    private javax.swing.JTextField jtfFechaSolicitud;
    private javax.swing.JTextField jtfSolicitante;
    // End of variables declaration//GEN-END:variables
}
